<script>
    function addQueryParam(url, param) {
        // 如果URL中已经有查询参数，则使用"&"来添加新参数  
        // 如果没有，则使用"?"来添加第一个参数  
        let separator = url.indexOf("?") !== -1 ? "&" : "?";
        // 添加参数到URL  
        return url + separator + param;
    }
    const url = "/api/rest/dept/all";
    let data = [];
    const columns = [

        {
            id: "namePath",
            name: "名称",
        },
        {
            id: "id",
            name: "编号",
        },
        {
            id: "type",
            name: "类型",
        },
        {
            id: "enableState",
            name: "状态",
        },
        {
            id: "principal",
            name: "负责人",
        },
        {
            id: "phone",
            name: "电话",
        },
        {
            id: "updateAt",
            name: "更新时间",
        },

        {
            name: "操作",
            width: "23%",
            formatter: (_, row) =>
                gridjs.html(`
      <button id="resetPwdButton" type="button" data-bs-toggle="modal" data-bs-target="#resetPwdModal" class="btn btn-sm btn-warning m-1">
        <i class="bi bi-lock" ></i>重置密码
        </button>
      `),
        },
    ];
    const server = {
        url,
        then: (data) => {
            this.data = data.content;
            return data.content.map((item) => [
                item.namePath,
                item.id,
                item.type,
                item.enableState,
                item.principal,
                item.phone,
                item.updateAt ? moment(item.updateAt).format("YYYY-MM-DD hh:mm:ss") : "",
            ]);
        },
        total: (data) => data.totalElements,
    };
    const pagination = {
        limit: 10,
        server: {
            url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`),
        },
    };
    const options = {
        columns,
        server,
        pagination,
        language: gridjs.l10n.cnCN,
    };
    window.onload = function () {
        const grid = new gridjs.Grid(options);
        grid.render(dataTable);
        searchForm.addEventListener("submit", (event) => {
            event.preventDefault();
            const formData = new FormData();
            formData.set("namePath", searchForm.namePath.value.trim());

            // formData.set("type", searchForm.type.value.trim());
            formData.set("enableState", searchForm.enableState.value);
            // formData.set("principal", searchForm.principal.value.trim());
            formData.set("phone", searchForm.phone.value.trim());
            const searchParams = new URLSearchParams(formData);
            options.server.url = addQueryParam(url, searchParams.toString());
            grid.updateConfig(options).forceRender();
        });
        grid.on("cellClick", (...args) => {
            const event = args[0];
            const userId = args[3].cells[0].data;
            if (event.target?.id === "resetPwdButton") {
                resetPwdForm.id.value = userId;
            }
        });
        重置密码表单提交处理事件
        resetPwdForm.addEventListener("submit", (event) => {
            event.preventDefault();
            if (resetPwdForm.checkValidity()) {
                const formData = Object.fromEntries(new FormData(resetPwdForm));
                fetch(`${url}/${formData.id}/update-password`, {
                    method: "PATCH",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(formData),
                }).then((response) => {
                    if (response.ok) {
                        var button = resetPwdForm.querySelector('[name="close"]');
                        var event = new Event("click");
                        button.dispatchEvent(event);
                        grid.updateConfig(options).forceRender();
                    } else {
                        response.json().then((data) => {
                            alert(data.message, "danger", document.getElementById("alertResetMessage"));
                        });
                    }
                });
            } else {
                resetForm.classList.add("was-validated");
            }
        });
    };
</script>